import React, { Component } from 'react';
import { base, ajax, toast, getMultiLang} from 'nc-lightapp-front';
const { NCButton: Button, NCCheckbox:Checkbox, NCNumber, NCModal: Modal, NCForm, NCDiv } = base;
const { NCFormItem: FormItem } = NCForm;

import { CheckboxItem, RadioItem, SelectItem } from '../FormItems';
import ReferLoader from '../../ReferLoader/index.js'
import './index.less'
/**
 * 
 * 模板打印弹框
 * 接收父级参数：scopeGray, noRadio, showNum
 * 接收父级方法: handlePrint  handleCancel
 * 
 * scopeGray:true,radio置灰,默认false;
 * noCheckBox:true,不显示checkBox，默认false;
 * noRadio:true,不显示radio，默认false
 * showScopeall: 是否显示打印范围;true,显示;false,不显示;默认false
 * showOrderunify: 是否显示排页方式;true,显示;false,不显示;默认false
 * showNum:true,显示NcNum,默认false；visible：控制modal框是否显示
 * headData: form展示内容;formItemLayout:布局；formItemParam：属性
 * isPrintTerms: 是否是打印账簿的打印条件，true:是; false: 不是, 默认false
 * 
 */

const formItemLayout = { labelXs:3, labelSm:3, labelMd:3, xs:9, md:9, sm:9 };
const formItemLayoutNCNum = { labelXs:4, labelSm:4, labelMd:4, xs:8, md:8, sm:8 };
const formItemParam = { inline:true, showMast:false, isRequire:true, method:"change" };
const formItemlabelParam = { inline:true, showMast:true, isRequire:true, method:"change" };

export default class PrintModal extends Component {
    constructor(props) {
        super(props);
        this.state = this.getAllState()
        this.headData = []
    }
    componentWillMount(){
		let callback= (json) =>{
            this.setState({
              json:json
			},()=>{
                //initTemplate.call(this, this.props);
                this.headData = this.getHeadData()
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
    }
    componentDidMount() {
        this.props.PrintModalRef && this.props.PrintModalRef(this);
        let { appcode } = this.props;
        let { listItem } = this.state;
        if(!listItem.ctemplate.value){
            this.getDefaultPrintTemp(appcode).then((defaultemplate) => {
                listItem.ctemplate = { 
                    display: defaultemplate.refname || '', 
                    value: defaultemplate.refpk || '',
                    code: defaultemplate.refcode || '' 
                }
            })
        }
    }
    componentWillReceiveProps(nextProps){
        let { defaultAttachValue } = nextProps;
        let{ listItem } = this.state;
        listItem.attach.value =  defaultAttachValue;
        this.setState({
            listItem
        })
    }
    /**
     * @description: 获取模版
     * @param {*} appcode
     * @return {*}
     */
    getDefaultPrintTemp(appcode){
        let defaultemplate = {};
        let url = '/nccloud/gl/glpub/queryprinttemp.do';
        let data = { "queryCondition": { "isShowUnit": false, "isDataPowerEnable": true, "appcode": appcode } };
        return new Promise((resolve, reject) => {
            ajax({
                url: url,
                data: data,
                // async:false,
                success:function(response){
                    let { data, success } = response;
                    if(success){
                        if(data && data.rows && data.rows[0]){
                            defaultemplate = data.rows[0]
                        } else {
                            defaultemplate = { display: '', value: '',code: '' }
                        }
                    }
                    resolve(defaultemplate)
                },
            })
        })
    }
    //获取初始化state
    getInitState = () => {
        let initState = {
            listItem: {
                scopeall: { display: '', value: 'n' },  //打印范围
                ctemplate: { display: '', value: '',code: '' },  //模板
                orderunify: { display: '', value: 'false' },  //排页方式
                prepage: { display: '', value: 'n', checked: false },  //承前页
                downpage: { display: '', value: 'n', checked: false },  //过次页
                attach: { display: '', value: '1' }  //套打纸附页
            }
        }     
        return initState
    }
    //state中添加json
	getAllState = () => {
		let initState = this.getInitState()
		initState.json={}
		return initState
	}
	//初始化state
	setInitState = (printstate) => {
		if(JSON.stringify(printstate) !=='{}') {
			this.setState(printstate)
		} else {
            let initState = this.getInitState()
			this.setState(initState)
		}
    }
    // 弹框内容禁用
    setModalDisabled = (item, disabled) => {
        item.itemChild.map((child, index) => {
            child.disabled = disabled
        })
    }
    getHeadData = () => {
        let { json }=this.state
        let headData = [
            { 
                itemName: json['publiccomponents-000116'], 
                itemType: 'radio', 
                itemKey: 'scopeall', 
                itemChild: [
                    { value: 'n', label: json['publiccomponents-000117'] }, 
                    { value: 'y', label: json['publiccomponents-000118'] }
                ] 
            },/* 国际化处理： 打印范围:,当前,全部*/
            {
                itemName: json['publiccomponents-000119'], 
                itemType: 'refer', 
                itemKey: 'ctemplate',/* 国际化处理： 模板*/
                config: { refCode: "/gl/refer/voucher/PrintTemplateGridRef" }
            },
            { 
                itemName: json['publiccomponents-000120'], 
                itemType: 'radio', 
                itemKey: 'orderunify', 
                itemChild: [
                    { value: 'true', label: json['publiccomponents-000121'] }, 
                    { value: 'false', label: json['publiccomponents-000122'] }
                ] 
            },/* 国际化处理： 排页方式:,按年排页,按月排页*/
            { 
                itemName: json['publiccomponents-000124'], 
                itemType: 'checkbox', 
                itemKey: 'prepage'
            },/* 国际化处理： 承前页:,承前页*/
            { 
                itemName: json['publiccomponents-000126'], 
                itemType: 'checkbox', 
                itemKey: 'downpage'
            },/* 国际化处理： 过次页:,过次页*/
            { 
                itemName: json['publiccomponents-000127'], 
                itemType: 'ncNum', 
                itemKey: 'attach' 
            }/* 国际化处理： 套打纸附页:*/
        ]
        return headData
    }
    //获取返回父组件的值
	getConfirmData = (tempState) => {
        let { listItem } = tempState
        let baseData = {
            scopeall: '',
            ctemplate: '',
            // orderunify: '',
            prepage: '',
            downpage: '',
            attach: ''
        }
        for (const key in listItem) {
            if (listItem.hasOwnProperty(key)) {
                //账簿打印 用到排页方式（按年排页、按月排页）默认按月
                if(key==='orderunify') {
                    let tempOrderunify = listItem[key].value === 'false' ? false : true
                    baseData.byyear = tempOrderunify
                    baseData.bymonth = !tempOrderunify
                } else {
                    baseData[key] = listItem[key].value
                    // if(key==='ctemplate'){
                    //     baseData.nodekey = listItem.ctemplate.code
                    // }
                }
                
            }
        }
        return baseData
    }
    // 取消
    handleCancel() {
        let { handleCancel } = this.props
        if (handleCancel) {
            handleCancel()
        }
    }
    // 打印
    handlePrint() {
        let { handlePrint, isPrintTerms } = this.props
        let baseData = this.getConfirmData(this.state)
        if (handlePrint) {
            if(baseData.ctemplate){
                if(isPrintTerms){ 
                    baseData.scopeall = 'y' //打印条件的打印范围默认全部
                    handlePrint(baseData, this.state)
                } else {
                    handlePrint(baseData)
                }
            } else {
                toast({ content: this.state.json['publiccomponents-000128'], color: 'warning' });/* 国际化处理： 请选择打印模板*/
            }
            
        }
    }
    renderRadio(listItem, item, disabled) {
        let { scopeGray,noRadio, showScopeall, showOrderunify } = this.props
        // if (scopeGray && item.itemKey === 'scopeall') {
        //     item.itemChild.map((child, index) => {
        //         child.disabled = true
        //     })
        // }
        item.itemChild.map((child, index) => {
            child.disabled = disabled
        })
        if(!noRadio) {
            if((showScopeall && item.itemKey == 'scopeall') || (showOrderunify && item.itemKey == 'orderunify')) {
                return (
                    <FormItem
                        {...formItemLayout}
                        {...formItemParam}
                        labelName={item.itemName}
                    >
                        <RadioItem
                            name={item.itemKey}
                            type="customer"
                            defaultValue={listItem[item.itemKey].value ? listItem[item.itemKey].value : 'n'}
                            items={() => {
                                return (item.itemChild)
                            }}
                            onChange={(v) => {
                                listItem[item.itemKey].value = v
                                this.setState({
                                    listItem
                                })
                            }}
                        />
                    </FormItem>
                )
            }else{
                return <div/>
            }                         
        }else{
            return <div/>
        }
    }
    renderCheckbox(listItem, item, disabled) {
        let { noCheckBox } = this.props
        if (!noCheckBox) {
            return (
                <FormItem
                    {...formItemLayout}
                    {...formItemParam}
                    labelName={item.itemName}
                >
                    <Checkbox 
						checked={listItem[item.itemKey].checked} 
						disabled={disabled} 
						onChange={(v) => {
                            listItem[item.itemKey].value = (v == true) ? 'y' : 'n';
                            listItem[item.itemKey].checked = v
                            this.setState({
                                listItem
                            })
                        }}
					>
						{item.itemName }
					</Checkbox>
                </FormItem>
            )
        } else {
            return <div />
        }
    }
    renderReferLoader(listItem, item, disabled) {
        let referUrl = item.config.refCode + '/index.js';
        let defaultValue = {
            refname: listItem[item.itemKey].display, refpk: listItem[item.itemKey]
                .value
        };
        let { appcode, nodekey, printTermsUrl } = this.props
        return (
            <FormItem
                {...formItemLayout}
                {...formItemlabelParam}             
                labelName={item.itemName}
            >   
                <div className='refer-con'>
                    <ReferLoader
                        tag = 'test'
                        fieldid = 'printctemplate'                        
                        refcode = {referUrl}
                        value = {defaultValue}
                        disabled = {disabled}
                        printTermsUrl = {printTermsUrl}
                        queryCondition = {() => {
                            return {
                                "appcode": appcode,
                                // "nodekey": nodekey   //用不到
                            }
                        }}
                        onChange = {(v) => {
                            if(v.refpk){
                                listItem[item.itemKey].value = v.refpk
                                listItem[item.itemKey].display = v.refname
                                listItem[item.itemKey].code = v.refcode
                            }else{
                                listItem[item.itemKey] = { display: '', value: '',code: '' }
                            }
                        
                            this.setState({
                                listItem
                            })
                        }}
                    />
                </div>
                
            </FormItem>
        )
    }
    renderNCNumber(listItem, item, disabled) {
        let { showNum } = this.props
        if (showNum) {
            // listItem[item.itemKey].value = '1'
            return (
                <FormItem
                    {...formItemLayoutNCNum}
                    {...formItemParam}
                    labelName={item.itemName}
                >
                    <div className='ncnum'>
                        <span>{this.state.json['publiccomponents-000129']}</span>{/* 国际化处理： 第*/}
                        <NCNumber style={{ width: '80px' }}
                            scale={0}
                            fieldid='attach'
                            value={listItem[item.itemKey].value}
                            onChange={(val) => {
                                listItem[item.itemKey].value = val
                                this.setState({
                                    listItem
                                })
                            }}
                        />
                        <span>{this.state.json['publiccomponents-000130']}</span>{/* 国际化处理： 张*/}
                    </div>
                </FormItem>
            )
        } else {
            return <div />
        }
    }

    renderForm(listItem, disabled) {
        return (
            this.headData.map((item, i) => {
                switch (item.itemType) {
                    case 'radio':
                        return this.renderRadio(listItem, item, disabled)    
                    case 'checkbox':
                        return this.renderCheckbox(listItem, item, disabled)                       
                    case 'ncNum':
                        return this.renderNCNumber(listItem, item, disabled)
                    case 'refer':
                        return this.renderReferLoader(listItem, item, disabled)                       
                    default:
                        break;
                }
            })

        )
    }

    render() {
        let { visible, disabled } = this.props
        let { listItem, json } = this.state
        let tempDisabled = typeof disabled === 'boolean' ? disabled : false
        return (
            <div className='printModal'>
                <Modal style={{ width: '520px',minHeight:'268px',maxHeight:'525px' }} fieldid='print' show={visible} onHide={this.handleCancel.bind(this)} id="printsun">
                    <Modal.Header closeButton={true}>
                        <Modal.Title>{json['publiccomponents-000131']}</Modal.Title>{/* 国际化处理： 打印*/}
                    </Modal.Header >
                    <Modal.Body className='print-modal-body'>
                        <NCDiv fieldid="print" areaCode={NCDiv.config.FORM}>
                            <NCForm className='printform'
                                useRow={true}
                                submitAreaClassName='classArea'
                                showSubmit={false}　>
                                {this.renderForm(listItem, tempDisabled)}
                            </NCForm>
                        </NCDiv>    
                    </Modal.Body>
                    <Modal.Footer >
                        <Button size="sm" fieldid='confirm' colors="primary" disabled={disabled} onClick={this.handlePrint.bind(this)}>{json['publiccomponents-000009']}</Button>{/* 国际化处理： 确定*/}
                        <Button fieldid='cancel' onClick={this.handleCancel.bind(this)}>{json['publiccomponents-000010']}</Button>{/* 国际化处理： 取消*/}
                    </Modal.Footer>
                </Modal>
            </div >

        )
    }
}


